import { debounce } from '@/utils'

export default {
  data() {
    return {
      $_sidebarElm: null,
      $_resizeHandler: null,
      $_resizeObserver: null,
      $_isResizing: false
    }
  },
  mounted() {
    this.initListener()
  },
  activated() {
    if (!this.$_resizeHandler) {
      // avoid duplication init
      this.initListener()
    }

    // when keep-alive chart activated, auto resize
    this.resize()
  },
  beforeDestroy() {
    this.destroyListener()
  },
  deactivated() {
    this.destroyListener()
  },
  methods: {
    // use $_ for mixins properties
    // https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential
    $_sidebarResizeHandler(e) {
      if (e.propertyName === 'width') {
        this.$_resizeHandler()
      }
    },
    initListener() {
      // 增加防抖时间，避免ResizeObserver循环通知
      this.$_resizeHandler = debounce(() => {
        // 防止重复调用
        if (this.$_isResizing) return
        this.$_isResizing = true
        
        try {
          this.resize()
        } catch (error) {
          console.warn('Chart resize error:', error)
        } finally {
          // 使用requestAnimationFrame确保在下一帧重置状态
          this.$nextTick(() => {
            requestAnimationFrame(() => {
              this.$_isResizing = false
            })
          })
        }
      }, 200) // 增加防抖时间到200ms
      
      window.addEventListener('resize', this.$_resizeHandler, { passive: true })

      this.$_sidebarElm = document.getElementsByClassName('sidebar-container')[0]
      this.$_sidebarElm && this.$_sidebarElm.addEventListener('transitionend', this.$_sidebarResizeHandler, { passive: true })
    },
    destroyListener() {
      window.removeEventListener('resize', this.$_resizeHandler)
      this.$_resizeHandler = null
      this.$_isResizing = false

      this.$_sidebarElm && this.$_sidebarElm.removeEventListener('transitionend', this.$_sidebarResizeHandler)
      
      // 清理ResizeObserver
      if (this.$_resizeObserver) {
        this.$_resizeObserver.disconnect()
        this.$_resizeObserver = null
      }
    },
    resize() {
      const { chart } = this
      if (chart && typeof chart.resize === 'function') {
        // 添加异常处理，避免resize过程中的错误
        try {
          chart.resize()
        } catch (error) {
          console.warn('Chart resize failed:', error)
        }
      }
    }
  }
}
